package com.sunshine.problem.breakdown;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.sunshine.domain.Shop;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @author Mokairui
 * @description 处理缓存穿透的问题, 缓存空对象
 * @since 2022/12/18
 */
public class Solution {
    private static final String CACHE_SHOP_KEY = "CACHE:SHOP:KEY";
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    public ResponseEntity<Shop> queryById(Long id) {
        return ResponseEntity.ok(queryWithPassThrough(id));
    }

    private Shop queryWithPassThrough(Long id) {
        String key = CACHE_SHOP_KEY + id;
        // 1.从redis查询商城缓存
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        // 2.判断是否存在
        if (StrUtil.isNotBlank(shopJson)) {
            // 3.存在直接返回
            return JSONUtil.toBean(shopJson, Shop.class);
        }

        if (shopJson != null) {
            return null;
        }

        // 实现缓存重建
        Shop shop = null;
        String lockKey = "lock:shop:" + id;
        try {
            if (!tryLock(lockKey)) {
                TimeUnit.SECONDS.sleep(10L);
                queryWithPassThrough(id);
            }

            // 4.不存在,根据id查询数据库
            shop = getShopById(id);

            // 5.不存在,将空值写入redis
            if (shop == null) {
                stringRedisTemplate.opsForValue().set(key, "", 2L, TimeUnit.MINUTES);
                // 6.返回错误信息
                return null;
            }
            stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop), 10L, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            unlock(lockKey);
        }
        // 7. 存在返回商品信息
        return shop;
    }

    private boolean tryLock(String key) {
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10L, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }
    
    private boolean unlock(String key) {
        return BooleanUtil.isTrue(stringRedisTemplate.delete(key));
    }
    
    public Shop getShopById(Long id) {
        // 模拟从数据库查询 shop 信息
        return new Shop();
    }

}
